package addressBook;

import java.awt.event.*;

public class newContactWindowController implements ActionListener{
	
	private newContactWindowView theView;
	
	public newContactWindowController(newContactWindowView theView, newContactWindowModel theModel)
	{
		this.theView = theView;
		
		this.theView.addButtonListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		String[] contact = new String[7];
		contact c = new contact(contact);
		
		// Surround interactions with the view with
		// a try block in case field(s) weren't
		// properly entered
		
		try{
		
			c.setFirstName(theView.getFirstName());
			c.setLastName(theView.getLastName());
			c.setPersoHomeNum(theView.getPhoneNumber());
			c.setAddress(theView.getAddress());
			c.setCity(theView.getCity());
			c.setUrl(theView.getUrl());
			c.setEmail(theView.getEmail());
			
			if(c.getFirstName().isEmpty()||isInteger(c.getFirstName()))
				throw new IllegalArgumentException("Enter First Name (only letters)!");
			else if(c.getLastName().isEmpty()||isInteger(c.getLastName()))
				throw new IllegalArgumentException("Enter Last Name (only letters)!");
			else if(c.getPersoHomeNum().isEmpty()||!isInteger(c.getPersoHomeNum()))
				throw new IllegalArgumentException("Enter Phone Number (only numbers)!");
			else if(c.getAddress().isEmpty()||!isIntegerAt(c.getAddress()))
				throw new IllegalArgumentException("Enter Street Address (must start with a number)!");
			else if(c.getCity().isEmpty()&&!isInteger(c.getCity()))
				throw new IllegalArgumentException("Enter City (only letters)!");
			else if(c.getUrl().isEmpty())
				throw new IllegalArgumentException("Enter Url!");
			else if(c.getEmail().isEmpty())
				throw new IllegalArgumentException("Enter Email!");
			else
				theView.myContacts.addContact(c);
	        	theView.myContacts.sortContacts(theView.myContacts.getArg());
				theView.setVisible(false);
				
		}

		catch(IllegalArgumentException ex){
			
			theView.displayErrorMessage(ex);
			
		}
	}
	
	public static boolean isInteger(String str) {
		if (str == null) {
			return false;
		}
		int length = str.length();
		if (length == 0) {
			return false;
		}
		int i = 0;
		if (str.charAt(0) == '-') {
			if (length == 1) {
				return false;
			}
			i = 1;
		}
		for (; i < length; i++) {
			char c = str.charAt(i);
			if (c <= '/' || c >= ':') {
				return false;
			}
		}
		return true;
	}
	
	public static boolean isIntegerAt(String str) {
		boolean bool = false;
		if (str == null) {
			return false;
		}
		int length = str.length();
		if (length == 0) {
			return false;
		}
		if (str.charAt(0) == '0'||str.charAt(0) == '1'||str.charAt(0) == '2'||str.charAt(0) == '3'||str.charAt(0) == '4'||str.charAt(0) == '5'||str.charAt(0) == '6'||str.charAt(0) == '7'||str.charAt(0) == '8'||str.charAt(0) == '9') {
			bool = true;
		}
		return bool;
	}
	
}
